﻿package net.jmp0.toast.entities.obstacles 
{
	import net.jmp0.toast.entities.bases.GameElement;
	import net.jmp0.toast.entities.interfaces.wobblingBehavior.DontWobble;
	import net.jmp0.toast.entities.obstacles.Obstacle;
	import net.jmp0.toast.entities.player.Player;
	import punk.core.Entity;
	
	/**
	 * ...
	 * @author Thodd
	 */
	public class Pushable extends Obstacle
	{
		//Sprite
		[Embed(source = '../../res/pushable.png')] private var imgSprite:Class;
		
		/**
		 * Constructor
		 * @param	x : it's obvious isn't it?
		 * @param	y : you get it
		 */
		public function Pushable(x:int, y:int) {
			super(x, y);
			
			//Standard setup stuff
			this.sprite = FP.getSprite(imgSprite, 20, 20, false, false, 0, 0, true);
			this.randomizeAnimation();
			
			//disable wobbling
			this.wobblingBehavior = new DontWobble(this);
			
		}
	
		
		override public function update():void {
		
			//Moving
			if (xSpeed != 0 || ySpeed != 0) {
				performMovement();
			}
			
			//destroy if outside level
			if (x > FP.screen.width || 	x < 0 ||
				y > FP.screen.height || y < 0) {
					
				this.destroy();
			}
			
		}
		
		
		/**
		 * Moves the pushable and handles collisions
		 * Essentially the same code as the playermovement, much simpler though
		 */
		private function performMovement():void {
			
			var travelingDistance:int = (xSpeed != 0) ? xSpeed : ySpeed;
			
			//Move the pushable block
			for (var i:int = 0; i < Math.abs(travelingDistance); i++) {
				//Check for a collision
				var collisionEntity:Entity = this.collide("obstacle", x + FP.sign(xSpeed), y + FP.sign(ySpeed));

				//If there is none, then move the player
				// "lastCollision" is used to prevent double collision performing
				if (collisionEntity == null || collisionEntity == lastCollision) {
					x += FP.sign(xSpeed);
					y += FP.sign(ySpeed);
					
				}else if (collisionEntity != null) {
					//reset the last collision
					lastCollision = null;
					//if there was a collision, downcast the entity to a GameElement instance
					if (collisionEntity is GameElement) {
						var ge:GameElement = collisionEntity as GameElement;
						//lets wobble!
						ge.getWobblingBehavior().wobble(this);
						
						//stop the movement if there was a collision
						oldXspeed = xSpeed;
						oldYspeed = ySpeed;
						xSpeed = 0;
						ySpeed = 0;
						isMoving = false;
						
						//Only perform collision with obstacles other than keys and oranges
						//it would be stupid if a pushable could steal your keys and oranges
						//this means a pushable can not pass through an orange or a key
						//AND: we don't want a pushable to trigger a levelchange by touching a Goal instance
						if(!(ge is GameKey) && !(ge is MagicOrange) && !(ge is Goal) && !(ge is Player)){
							ge.performCollision(this);
						}
						
					}
					
				}
				
			}
			
		}
	}

}